package com.dm.wallpaper.library.utils;

import com.dm.wallpaper.library.preferences.Preferences;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.agp.utils.Point;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.data.rdb.ValuesBucket;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.URI;
import java.nio.file.*;
import java.util.Iterator;
import java.util.Random;

/*
 * Copyright (C) 2021 The Chinese Software International Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
public class SystemUtils {
    Random random;

    private SystemUtils() {
        random=new Random();
    }

    private static SystemUtils instance;

    public static SystemUtils getInstance() {
        if (instance == null) {
            instance = new SystemUtils();
        }
        return instance;
    }


    public static float fp2px(Context context, float fp) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        float sca = display.getAttributes().scalDensity;
        return (float) (fp * sca + (double)0.5 * (fp >= 0 ? 1 : -1));
    }

    public static float vp2px(Context context, float vp) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        float dpi = display.getAttributes().densityPixels;
        return (float) (vp * dpi + (double)0.5 * (vp >= 0 ? 1 : -1));
    }

    public static String getString(Context context, int StringID) {
        try {
            return context.getResourceManager().getElement(StringID).getString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static int getDisplayWidthInPx(Context context) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        Point point = new Point();
        display.getSize(point);
        return (int) point.getPointX();
    }

    public static int getDisplayHightInPx(Context context) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        Point point = new Point();
        display.getSize(point);
        return (int) point.getPointY();
    }

    //获取文件夹大小
    public static long getDirectorySize(File file) {
        if (file.exists()) {
            long result = 0L;
            File[] fileList = file.listFiles();
            File[] var4 = fileList;
            int var5 = fileList.length;

            for (int var6 = 0; var6 < var5; ++var6) {
                File aFileList = var4[var6];
                if (aFileList.isDirectory()) {
                    result += getDirectorySize(aFileList);
                } else {
                    result += aFileList.length();
                }
            }

            return result;
        } else {
            return 0L;
        }
    }


    public static void clearDirectory(File file) throws IOException {
        if (file.isDirectory()) {
            File[] var2 = file.listFiles();
            int var3 = var2.length;

            for (int var4 = 0; var4 < var3; ++var4) {
                File child = var2[var4];
                clearDirectory(child);
            }
        }
        Files.delete(file.toPath());
    }


    //将图片保存到相册
    public static Uri saveImage(String fileName, PixelMap pixelMap, Context context) {
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");
            //应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            //这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);
            packingOptions.format = "image/jpeg";
            packingOptions.quality = 90;
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);
            if (result) {
                result = imagePacker.addImage(pixelMap);
                if (result) {
                    long dataSize = imagePacker.finalizePacking();
                }
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            //解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            Preferences.get().setKeyAndVelue(fileName, uri.toString());
            return uri;
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("SystemUtils.saveImage([fileName, pixelMap, context]):125");
        }
        return null;
    }


    /**
     * solr检索时，转换特殊字符
     *
     * @param s 需要转义的字符串
     * @return 返回转义后的字符串
     */
    public static String escapeQueryChars(String s) {
        if (StringUtils.isBlank(s)) {
            return s;
        }
        StringBuilder sb = new StringBuilder();
        //查询字符串一般不会太长，挨个遍历也花费不了多少时间
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // These characters are part of the query syntax and must be escaped
            if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')'
                    || c == ':' || c == '^' || c == '[' || c == ']' || c == '\"'
                    || c == '{' || c == '}' || c == '~' || c == '*' || c == '?'
                    || c == '|' || c == '&' || c == ';' || c == '/' || c == '.'
                    || c == '$' || Character.isWhitespace(c)) {
                sb.append('/');
            }
            sb.append(c);
        }
        return sb.toString();
    }


    public Random getRandom() {
        return random;
    }
}
